package com.imgrate.migration.controller;

import com.imgrate.migration.entity.User;
import com.imgrate.migration.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Random;

@RestController
@RequestMapping("/users")
@RequiredArgsConstructor
@Slf4j
@CrossOrigin(origins = "*")
public class UserController {
    
    private final UserService userService;
    
    @PostMapping
    public ResponseEntity<User> createUser(@RequestBody CreateUserRequest request) {
        try {
            log.info("创建用户请求: 用户名={}", request.getUsername());
            
            // 检查必填字段
            if (request.getUsername() == null || request.getUsername().isEmpty()) {
                return ResponseEntity.badRequest().build();
            }
            
            if (request.getPassword() == null || request.getPassword().isEmpty()) {
                return ResponseEntity.badRequest().build();
            }
            
            if (request.getEmail() == null || request.getEmail().isEmpty()) {
                return ResponseEntity.badRequest().build();
            }
            
            // 如果没有指定角色，默认为USER
            String role = request.getRole();
            if (role == null || role.isEmpty()) {
                role = "USER";
            }
            
            User createdUser = userService.createUserWithRole(
                request.getUsername(), 
                request.getPassword(), 
                request.getEmail(), 
                request.getFullName(),
                role
            );
            
            log.info("用户创建成功: ID={}, 用户名={}", createdUser.getId(), createdUser.getUsername());
            return ResponseEntity.ok(createdUser);
        } catch (Exception e) {
            log.error("创建用户失败: {}", e.getMessage(), e);
            return ResponseEntity.badRequest().build();
        }
    }
    
    @GetMapping
    public ResponseEntity<List<User>> getAllUsers() {
        try {
            List<User> users = userService.getAllUsers();
            return ResponseEntity.ok(users);
        } catch (Exception e) {
            log.error("获取用户列表失败: {}", e.getMessage(), e);
            return ResponseEntity.badRequest().build();
        }
    }
    
    @GetMapping("/{id}")
    public ResponseEntity<User> getUserById(@PathVariable Long id) {
        try {
            Optional<User> user = userService.findByUsername(id.toString());
            if (user.isPresent()) {
                return ResponseEntity.ok(user.get());
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            log.error("获取用户失败: {}", e.getMessage(), e);
            return ResponseEntity.badRequest().build();
        }
    }
    
    @PutMapping("/{id}")
    public ResponseEntity<User> updateUser(@PathVariable Long id, @RequestBody UpdateUserRequest request) {
        try {
            User updatedUser = userService.updateUser(id, request.getEmail(), request.getFullName());
            return ResponseEntity.ok(updatedUser);
        } catch (Exception e) {
            log.error("更新用户失败: {}", e.getMessage(), e);
            return ResponseEntity.badRequest().build();
        }
    }
    
    @PutMapping("/{id}/role")
    public ResponseEntity<User> updateUserRole(@PathVariable Long id, @RequestBody UpdateRoleRequest request) {
        try {
            User updatedUser = userService.updateUserRole(id, request.getRole());
            return ResponseEntity.ok(updatedUser);
        } catch (Exception e) {
            log.error("更新用户角色失败: {}", e.getMessage(), e);
            return ResponseEntity.badRequest().build();
        }
    }
    
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteUser(@PathVariable Long id) {
        try {
            userService.deleteUser(id);
            return ResponseEntity.ok().build();
        } catch (Exception e) {
            log.error("删除用户失败: {}", e.getMessage(), e);
            return ResponseEntity.badRequest().build();
        }
    }
    
    @GetMapping("/stats")
    public ResponseEntity<Map<String, Object>> getUserStats() {
        try {
            Map<String, Object> stats = new HashMap<>();
            
            // 用户总数
            stats.put("totalUsers", userService.getUserCount());
            
            // 在线用户数（24小时内登录的用户）
            stats.put("onlineUsers", userService.getOnlineUsers().size());
            
            // 最近一周注册的用户数
            stats.put("newUsers", userService.getNewUsers().size());
            
            return ResponseEntity.ok(stats);
        } catch (Exception e) {
            log.error("获取用户统计信息失败: {}", e.getMessage(), e);
            return ResponseEntity.badRequest().build();
        }
    }
    
    @GetMapping("/role-stats")
    public ResponseEntity<Map<String, Long>> getUserRoleStats() {
        try {
            Map<String, Long> roleStats = new HashMap<>();
            
            // 获取所有用户
            List<User> users = userService.getAllUsers();
            
            // 统计各角色用户数
            for (User user : users) {
                String role = user.getRole();
                roleStats.put(role, roleStats.getOrDefault(role, 0L) + 1);
            }
            
            return ResponseEntity.ok(roleStats);
        } catch (Exception e) {
            log.error("获取用户角色统计信息失败: {}", e.getMessage(), e);
            return ResponseEntity.badRequest().build();
        }
    }
    
    @GetMapping("/growth-stats")
    public ResponseEntity<Map<String, Object>> getUserGrowthStats() {
        try {
            Map<String, Object> growthStats = new HashMap<>();
            
            // 获取最近7天的用户增长数据
            LocalDateTime now = LocalDateTime.now();
            Map<String, Integer> dailyStats = new HashMap<>();
            
            for (int i = 6; i >= 0; i--) {
                LocalDateTime date = now.minusDays(i);
                LocalDateTime startOfDay = date.withHour(0).withMinute(0).withSecond(0);
                LocalDateTime endOfDay = date.withHour(23).withMinute(59).withSecond(59);
                
                List<User> users = userService.getUsersByTimeRange(startOfDay, endOfDay);
                String dateKey = date.format(java.time.format.DateTimeFormatter.ofPattern("MM-dd"));
                dailyStats.put(dateKey, users.size());
            }
            
            growthStats.put("dailyStats", dailyStats);
            return ResponseEntity.ok(growthStats);
        } catch (Exception e) {
            log.error("获取用户增长统计信息失败: {}", e.getMessage(), e);
            return ResponseEntity.badRequest().build();
        }
    }
    
    @GetMapping("/new")
    public ResponseEntity<List<User>> getNewUsers() {
        try {
            List<User> users = userService.getNewUsers();
            return ResponseEntity.ok(users);
        } catch (Exception e) {
            log.error("获取新用户列表失败: {}", e.getMessage(), e);
            return ResponseEntity.badRequest().build();
        }
    }
    
    @GetMapping("/online")
    public ResponseEntity<List<User>> getOnlineUsers() {
        try {
            List<User> users = userService.getOnlineUsers();
            return ResponseEntity.ok(users);
        } catch (Exception e) {
            log.error("获取在线用户列表失败: {}", e.getMessage(), e);
            return ResponseEntity.badRequest().build();
        }
    }
    
    @PostMapping("/import")
    public ResponseEntity<Map<String, Object>> importUsers(@RequestParam("file") MultipartFile file) {
        try {
            log.info("开始导入用户数据，文件名: {}", file.getOriginalFilename());
            
            // 检查文件类型
            if (!file.getOriginalFilename().endsWith(".csv")) {
                Map<String, Object> response = new HashMap<>();
                response.put("success", false);
                response.put("message", "只能上传CSV文件");
                return ResponseEntity.badRequest().body(response);
            }
            
            // 解析CSV文件
            List<UserImportDto> usersToImport = parseCsvFile(file);
            
            // 导入用户
            int successCount = 0;
            int failCount = 0;
            List<String> errors = new ArrayList<>();
            
            for (UserImportDto userDto : usersToImport) {
                try {
                    // 检查用户名是否已存在
                    if (userService.findByUsername(userDto.getUsername()).isPresent()) {
                        errors.add("用户名已存在: " + userDto.getUsername());
                        failCount++;
                        continue;
                    }
                    
                    // 检查邮箱是否已存在
                    if (userService.existsByEmail(userDto.getEmail())) {
                        errors.add("邮箱已存在: " + userDto.getEmail());
                        failCount++;
                        continue;
                    }
                    
                    // 生成随机密码（如果未提供）
                    String password = userDto.getPassword();
                    if (password == null || password.isEmpty()) {
                        password = generateRandomPassword(8);
                    }
                    
                    // 创建用户
                    userService.createUser(
                        userDto.getUsername(),
                        password,
                        userDto.getEmail(),
                        userDto.getFullName()
                    );
                    
                    successCount++;
                } catch (Exception e) {
                    log.error("导入用户失败: {}", e.getMessage(), e);
                    errors.add("导入用户失败 " + userDto.getUsername() + ": " + e.getMessage());
                    failCount++;
                }
            }
            
            // 返回结果
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("successCount", successCount);
            response.put("failCount", failCount);
            response.put("totalCount", usersToImport.size());
            response.put("errors", errors);
            
            log.info("用户导入完成，成功: {}, 失败: {}", successCount, failCount);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("导入用户数据失败: {}", e.getMessage(), e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "导入失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    private List<UserImportDto> parseCsvFile(MultipartFile file) throws IOException {
        List<UserImportDto> users = new ArrayList<>();
        
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(file.getInputStream(), StandardCharsets.UTF_8))) {
            String line;
            boolean isFirstLine = true;
            
            while ((line = reader.readLine()) != null) {
                // 跳过标题行
                if (isFirstLine) {
                    isFirstLine = false;
                    continue;
                }
                
                String[] fields = line.split(",");
                if (fields.length >= 4) {
                    UserImportDto user = new UserImportDto();
                    user.setUsername(fields[0].trim());
                    user.setEmail(fields[1].trim());
                    user.setFullName(fields[2].trim());
                    user.setPassword(fields[3].trim());
                    users.add(user);
                }
            }
        }
        
        return users;
    }
    
    private String generateRandomPassword(int length) {
        String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*";
        StringBuilder password = new StringBuilder();
        Random random = new Random();
        
        for (int i = 0; i < length; i++) {
            password.append(chars.charAt(random.nextInt(chars.length())));
        }
        
        return password.toString();
    }
    
    // 创建用户请求DTO
    public static class CreateUserRequest {
        private String username;
        private String password;
        private String email;
        private String fullName;
        private String role; // 添加角色字段
        
        // Getters and Setters
        public String getUsername() {
            return username;
        }
        
        public void setUsername(String username) {
            this.username = username;
        }
        
        public String getPassword() {
            return password;
        }
        
        public void setPassword(String password) {
            this.password = password;
        }
        
        public String getEmail() {
            return email;
        }
        
        public void setEmail(String email) {
            this.email = email;
        }
        
        public String getFullName() {
            return fullName;
        }
        
        public void setFullName(String fullName) {
            this.fullName = fullName;
        }
        
        public String getRole() {
            return role;
        }
        
        public void setRole(String role) {
            this.role = role;
        }
    }
    
    // 更新用户请求DTO
    public static class UpdateUserRequest {
        private String email;
        private String fullName;
        
        // Getters and Setters
        public String getEmail() {
            return email;
        }
        
        public void setEmail(String email) {
            this.email = email;
        }
        
        public String getFullName() {
            return fullName;
        }
        
        public void setFullName(String fullName) {
            this.fullName = fullName;
        }
    }
    
    // 更新密码请求DTO
    public static class UpdatePasswordRequest {
        private String newPassword;
        
        // Getters and Setters
        public String getNewPassword() {
            return newPassword;
        }
        
        public void setNewPassword(String newPassword) {
            this.newPassword = newPassword;
        }
    }
    
    // 更新角色请求DTO
    public static class UpdateRoleRequest {
        private String role;
        
        // Getters and Setters
        public String getRole() {
            return role;
        }
        
        public void setRole(String role) {
            this.role = role;
        }
    }
    
    // 用户导入DTO
    public static class UserImportDto {
        private String username;
        private String email;
        private String fullName;
        private String password;
        
        // Getters and Setters
        public String getUsername() {
            return username;
        }
        
        public void setUsername(String username) {
            this.username = username;
        }
        
        public String getEmail() {
            return email;
        }
        
        public void setEmail(String email) {
            this.email = email;
        }
        
        public String getFullName() {
            return fullName;
        }
        
        public void setFullName(String fullName) {
            this.fullName = fullName;
        }
        
        public String getPassword() {
            return password;
        }
        
        public void setPassword(String password) {
            this.password = password;
        }
    }
}